#import datetime
from datetime import datetime, date, timedelta
import operator

from django.db.models import Q
from django.views.generic import ListView
from django.views.generic import DetailView
from django.views.generic.simple import direct_to_template
from django.core.exceptions import ObjectDoesNotExist
from django.utils import simplejson as json
from django.http import HttpResponse
from django.core.paginator import Paginator

from app.models import * 

# TODO: change to generic view
def home(request):	
	city_list = []
	for city in City.objects.all().order_by('name'):		
		city_list.append({'id': city.id, 'name': city.name})
				
	business_list = []				
	for company_business in Company_Business.objects.all().order_by('business'):
		business_list.append({'id': company_business.id, 'business': company_business.business})
		
	oldest_company_entry = Company.objects.order_by('created')[:1].get()
	default_from_date = date.today() - timedelta(days = 2)
	default_to_date = date.today() - timedelta(days = 1)
	
	company_type_list = []
	for company_type in Company_Type.objects.all().order_by('type'):		
		company_type_list.append({'id': company_type.id, 'type': company_type.type})

	return direct_to_template(request, 'app/index.html', {'city_list': city_list,    
									   'business_list': business_list, 
									   'min_date_delta': (datetime.now().date() - oldest_company_entry.created).days,
									   'default_from_date': '%s.%s.%s' % (default_from_date.day, default_from_date.month, default_from_date.year),
									   'default_to_date': '%s.%s.%s' % (default_to_date.day, default_to_date.month, default_to_date.year),
									   'company_type_list': company_type_list})


class CompanyListView(ListView):	
	context_object_name = "company_list"
	template_name = "app/company_list.html"

	def get_queryset(self):
		company_location = self.request.GET.getlist('company_location')
		q_company_location = []
		for city_id in company_location:
			q_company_location.append(Q(address__city__id=city_id))
				
		from_date = datetime.strptime(self.request.GET.get('from_date'), '%d.%m.%Y')							
		to_date = datetime.strptime(self.request.GET.get('to_date'), '%d.%m.%Y')		
		q_create_date = Q(created__range=(from_date, to_date))
		
		company_type = self.request.GET.getlist('company_type')
		q_company_type = []
		for company_type_id in company_type:
			q_company_type.append(Q(company_type__id=company_type_id))
		
		business_type = self.request.GET.getlist('business_type')
		q_business_type = []
		for business_type_id in business_type:
			q_business_type.append(Q(business_list__id=business_type_id))
		
		return Company.objects.filter(reduce(operator.or_, q_company_location), q_create_date, reduce(operator.or_, q_company_type), reduce(operator.or_, q_business_type)).distinct()
	